package com.kime.email.javamail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

/**
 * 发送一封带有附件的邮件
 */
public class SendAttachEmail {

    // 发件人电子邮箱
    private static String from;
    // 发件人昵称
    private static String fromNickName;
    // 发件人密码/授权码
    private static String password;
    // 收件人电子邮箱
    private static String recipients;
    // 收件人昵称
    private static String recipientNickName;
    // 指定发送邮件的主机
    private static String senderHost;
    // 字符集编码
    private static String charset;
    // 邮件主题
    private static String subject;
    // 邮件正文
    private static String content;
    // 邮件正文字符集编码
    private static String contentCharset;
    // 附件内容
    private static String attachContent;

    /**
     * 通过加载器初始加载 attachEmailInfo.properties 文件，获取属性值
     */
    static {
        try {
            InputStream resource = ClassLoader.getSystemResourceAsStream("attachEmailInfo.properties");
            Properties properties = new Properties();
            properties.load(resource);
            from = properties.getProperty("email.from");
            fromNickName = properties.getProperty("email.from.nickName");
            password = properties.getProperty("email.password");
            recipients = properties.getProperty("email.recipients");
            recipientNickName = properties.getProperty("email.recipient.nickName");
            senderHost = properties.getProperty("email.senderHost");
            charset = properties.getProperty("email.charset");
            subject = properties.getProperty("email.subject");
            content = properties.getProperty("email.content");
            contentCharset = properties.getProperty("email.content.charset");
            attachContent = properties.getProperty("email.attach.content");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendEmail() {
        // 获取属性：用于配置属性
        Properties properties = new Properties();
        // 配置 SMTP 协议
        properties.setProperty("mail.transport.protocol", "smtp");
        // 配置发件人邮箱的 SMTP 服务器地址
        properties.setProperty("mail.smtp.host", senderHost);
        // 配置 SMTP 服务器地址端口
        properties.put("mail.smtp.port", 25);
        // 配置请求认证
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(properties, new MyAuthenticator(from, password));
        session.setDebug(true);
        try {
            // 创建一封带有附件的邮件
            MimeMessage message = createAttachMail(session);
            // 根据 session 获取邮件传输对象
            Transport transport = session.getTransport();
            // 连接邮件服务器
            transport.connect(from, password);
            // 发送邮件，发送所有的收件地址
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();
        } catch (Exception e) {
            System.out.println("创建邮件失败，请重新创建: "+ e.getMessage());
        }
    }

    /**
     * 创建一封带有附件的邮件
     */
    private MimeMessage createAttachMail(Session session) throws Exception{
        // 创建邮件信息
        MimeMessage mimeMessage = new MimeMessage(session);
        // 设置发件人电子邮箱
        mimeMessage.setFrom(new InternetAddress(from, fromNickName, charset));
        // 设置收件人电子邮箱
        mimeMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipients, recipientNickName, charset));
        // 设置邮件主题
        mimeMessage.setSubject(subject, charset);
        mimeMessage.setText(content,charset);
        /*
        设置附件组合方式：
            - new MimeMultipart("mixed") = mimeMultipart.setSubType("mixed")
        类型选择：
            - mixed：混合附件
            - alternative：可传送超文本
            - related：内嵌其他资源
         */
        MimeMultipart mimeMultipart = new MimeMultipart("mixed");
        // 创建节点
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        // 读取本地文件
        FileDataSource fileDataSource = new FileDataSource("D:\\workspace\\email-demo\\src\\main\\resources\\image\\oppo.png");
        DataHandler dataHandler = new DataHandler(fileDataSource);
        // 将文件读取到节点
        mimeBodyPart.setDataHandler(dataHandler);
        // 设置节点唯一编号
        mimeBodyPart.setContentID("oppoImage");
        // 设置节点文件名称
        mimeBodyPart.setFileName("oppo.png");
        // 创建节点
        MimeBodyPart linkMimeBodyPart = new MimeBodyPart();
        // 以链接的方式添加内容
        linkMimeBodyPart.setContent(attachContent, contentCharset);
        // 将节点组合到附件中
        mimeMultipart.addBodyPart(linkMimeBodyPart);
        mimeMultipart.addBodyPart(mimeBodyPart);
        // 设置邮件正文
        mimeMessage.setContent(mimeMultipart);
        // 设置邮件发送时间
        mimeMessage.setSentDate(new Date());
        // 保存设置
        mimeMessage.saveChanges();
        return mimeMessage;
    }

    public static void main(String[] args) {
        SendAttachEmail sendAttachEmail = new SendAttachEmail();
        sendAttachEmail.sendEmail();
    }

}
